package com.cht.commonUtil.deployment;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.as.cli.CommandContext;

import com.cht.commonUtil.structure.I1S1;
import com.cht.commonUtil.structure.S4;
import com.cht.commonUtil.webInit.SP;
import com.cht.commonUtil.widgets.Widgets;
import com.google.gson.Gson;

public class ValidateEnv4Dep extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


		request.setCharacterEncoding( SP.UIcodeSet );
		response.setCharacterEncoding( SP.UIcodeSet );
		response.setContentType("application/json");
		
		
		/**
		 *	0.	檢查程式初始化
		 *	1.	選定的環境存在
		 *	2.	確認環境下有綁定Squad
		 *	3.	綁定的Squad存在
		 *	4.	綁定的Squad內要有Server Group的連線資訊
		 *	5.	綁定的Squad內的Server Group連線資訊可連線
		 *	6.	綁定的Squad，以下有設定主機
		 *	7.	綁定的Squad，以下設定的主機有登入資訊
		 *	8.	綁定的Squad，以下設定的主機可以連線
		 *	9.	綁定的Squad，以下設定的主機可以連線，但其不能執行service httpd指令
		 *	99.	完全通過，開始部署 
		 */
		
		String bssId = "fOrder";
		String subsysId = request.getParameter("subsysId");
		String envId = request.getParameter("envId");
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		CommandContext cmdCtx = null;
		
		String sql = "";
		I1S1 res = new I1S1();
		
		
		try {
			conn = Widgets.getConn();
			boolean isPerformHTTPD = Boolean.parseBoolean( Widgets.getSysParameter("isPerformHTTPD") );
			
			// 1.	選定的環境存在
			sql = "SELECT COUNT(*) FROM env WHERE subsysId=? AND envId=?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, subsysId);
			ps.setString(2, envId);
			rs = ps.executeQuery();
			rs.next();
			if( rs.getInt(1) == 0 ) {
				res.setI1(1);
				res.setS1("選定的環境 "+envId+"已不存在");
			} else {
				//	2.	確認環境下有綁定Squad
				if (rs != null) {rs.close();}
				if (ps!= null) {ps.close();}
				
				sql = "SELECT COUNT(*) FROM mpsquadenv WHERE bssId=? AND subsysId=? AND envId=?";
				ps = conn.prepareStatement(sql);
				ps.setString(1, bssId);
				ps.setString(2, subsysId);
				ps.setString(3, envId);
				rs = ps.executeQuery();
				rs.next();
				int mpSquadNum = rs.getInt(1);	//環境下所綁定的squad數
				if( mpSquadNum == 0 ) {
					res.setI1(2);
					res.setS1("環境"+envId+"，尚未為其設定Server Group");
				} else {
					//	3.	綁定的Squad存在
					ArrayList<String> squads = new ArrayList<String>();	//此環境下的 squad清單
					sql = "SELECT t1.squadId FROM squad t1,mpsquadenv t2 WHERE t1.subsysId=t2.subsysId AND t1.squadId=t2.squadId AND t2.bssId=? AND t2.subsysId=? AND t2.envId=?";
					ps = conn.prepareStatement(sql);
					ps.setString(1, bssId);
					ps.setString(2, subsysId);
					ps.setString(3, envId);
					rs = ps.executeQuery();
					while ( rs.next() ) {
						squads.add( rs.getString("squadId") );
					}
					
					int squadExistNum = squads.size();	//squad在其table內的數目
					if ( squadExistNum != mpSquadNum ) {
						res.setI1(3);	//綁定的Squad存在
						res.setS1("環境"+envId+"下所綁定的Server Group並不存在於ServerGroup的基本設定檔中");
					} else {
						sql = "SELECT COUNT(*) FROM mpsquadenv WHERE bssId=? AND subsysId=? AND envId=? AND cip IS NOT NULL AND cid IS NOT NULL AND cpwd IS NOT NULL AND cport IS NOT NULL";
						ps = conn.prepareStatement(sql);
						ps.setString(1, bssId);
						ps.setString(2, subsysId);
						ps.setString(3, envId);
						rs = ps.executeQuery();
						rs.next();
						if ( squadExistNum != rs.getInt(1) ) {
							res.setI1(4);	//	4.	綁定的Squad內要有Server Group的連線資訊
							res.setS1("環境"+envId+"下所設定的Server Group，尚未設定 AP Server管理介面連線資訊");
						} else {
							boolean is5pass = true;
							sql = "SELECT cip,cid,cpwd,cport FROM mpsquadenv WHERE bssId=? AND subsysId=? AND envId=? AND squadId=?";
							ps = conn.prepareStatement(sql);
							ps.setString(1, bssId);
							ps.setString(2, subsysId);
							ps.setString(3, envId);
							for ( int i=0;i<squads.size();i++) {
								ps.setString(4, squads.get(i) );
								rs = ps.executeQuery();
								rs.next();
								try {
									cmdCtx = Widgets.initCommandContext(rs.getString("cip"), rs.getInt("cport"), rs.getString("cid"), rs.getString("cpwd").toCharArray() );
									cmdCtx.disconnectController();
									cmdCtx.terminateSession();
								} catch( Exception e) {
									Widgets.errLog(e);
									res.setS1("Server Group："+squads.get(i)+"，無法連線 AP Server管理介面");
									is5pass = false;
									break;
								}
							}
							if ( !is5pass ) {
								res.setI1(5); //	5.	綁定的Squad內的Server Group連線資訊可連線
							} else {
								boolean is6pass = true;
								
								ArrayList<S4> hosts = new ArrayList<S4>();
								sql = "SELECT ip,port FROM mpsquadhosts WHERE subsysId=? AND envId=? AND squadId=?";
								ps = conn.prepareStatement(sql);
								ps.setString(1, subsysId);
								ps.setString(2, envId);
								for ( int i=0;i<squads.size();i++) {
									ps.setString(3, squads.get(i) );
									rs = ps.executeQuery();
									if ( rs.next() ) {
										S4 host = new S4();	// s1是ip,s2是port,s3是id,s4是pwd
										host.setS1( rs.getString("ip") );
										host.setS2( String.valueOf( rs.getInt("port") ) );
										hosts.add(host);
									} else {
										res.setS1("Server Group："+squads.get(i)+"下，並無設定主機");
										is6pass = false;
										break;										
									}
								}
								if ( isPerformHTTPD && !is6pass ) {
									res.setI1(6);	//	檢查 6.	綁定的Squad，以下有設定主機
								} else {	//接著測試綁定的Squad，以下設定的主機有登入資訊
									boolean is7pass = true;
									sql="SELECT loginId,loginPWD FROM hosts WHERE subsysId=? AND ip=? AND port=?";
									ps = conn.prepareStatement(sql);
									ps.setString(1, subsysId);
									for(int i=0; i<hosts.size();i++ ) {
										ps.setString(2, hosts.get(i).getS1() );
										ps.setInt(3, Integer.parseInt( hosts.get(i).getS2() ));
										rs = ps.executeQuery();
										if( rs.next() ) {
											hosts.get(i).setS3( rs.getString("loginId") );
											hosts.get(i).setS4( rs.getString("loginPWD") );
										} else {
											res.setS1("Server Group："+squads.get(i)+"下的主機："+hosts.get(i)+"並無設定連線資訊");
											is7pass = false;
											break;			
										}
									}
									if ( isPerformHTTPD && !is7pass ) {
										res.setI1(7);	//綁定的Squad，以下設定的主機有登入資訊
									} else {	//綁定的Squad，以下設定的主機可以連線
										boolean is8pass = true;
										for(int i=0; i<hosts.size();i++ ) {
											int result = Widgets.chkHostConnection(hosts.get(i).getS1(),hosts.get(i).getS3(), hosts.get(i).getS4());
											if( result != 99 ) {
												res.setS1("Server Group："+squads.get(i)+"下的主機："+hosts.get(i).getS1()+"，連線失敗");
												is8pass = false;
												break;
											}
										}
										
										if ( isPerformHTTPD && !is8pass ) {
											res.setI1(8);	//綁定的Squad，以下設定的主機可以連線
										} else {
											boolean is9pass = true;
											
											if ( isPerformHTTPD ) { //需要執行的前提httpd的前提下才執行測試
												for(int i=0; i<hosts.size();i++ ) {
													String result = Widgets.chkServiceStatus(hosts.get(i).getS1(),hosts.get(i).getS3(), hosts.get(i).getS4());
													System.out.println("檢查"+hosts.get(i).getS1()+" 執行HTTPD的結果");
													System.out.println(result);
													if( !( (result.trim()).equalsIgnoreCase("httpd is stopped".trim()) || result.contains("httpd (pid")) ) {
														res.setS1("Server Group："+squads.get(i)+"下的主機："+hosts.get(i).getS3()+"，無法執行service httpd指令");
														is9pass = false;
														break;
													}
												}
											}
											
											if ( is9pass ) {
												res.setI1(99);	//完全過關
											} else {
												res.setI1(9);	//綁定的Squad，以下設定的主機可以連線，但其不能執行service httpd指令
											}
										}
									}
								}
							}
						}
					}
				}
			}
		} catch ( Exception e) {
			res.setS1("發生不在預期的錯誤,請通知系統管理員<p><p>"+Widgets.errLog(e) );
		} finally {
			try {
				if (rs != null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
				if (cmdCtx != null) {
					cmdCtx.disconnectController();
					cmdCtx.terminateSession();
				}
			} catch (SQLException e) { e.printStackTrace(); }
		}
		
		response.getWriter().write( new Gson().toJson(res) );
	}
}
